import Vue from "vue";
import {getNowDate} from "@/util/util";


export default {
    namespaced: true,
    state: {
        token: "",
        username: "",
        realname: "",
        info: {},
        welcome: "",
    },
    getters: {},
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
            // 同步更新到本地存储
            Vue.ls.set(window.global_value.TOKEN_KEY, token);
        },
        SET_NAME: (state, {username, realname, welcome}) => {
            state.username = username;
            state.realname = realname;
            state.welcome = welcome;
            // 同步更新到本地存储
            Vue.ls.set("username", username);
        },
        SET_INFO: (state, info) => {
            state.info = info;
            // 同步更新到本地存储
            Vue.ls.set("userInfo", JSON.stringify(info));
        },
        // 新增：清除用户信息
        CLEAR_USER_INFO: (state) => {
            state.token = "";
            state.username = "";
            state.realname = "";
            state.info = {};
            state.welcome = "";
            // 清除本地存储
            Vue.ls.remove(window.global_value.TOKEN_KEY);
            Vue.ls.remove("userInfo");
            Vue.ls.remove("username");
        }
    },
    actions: {
        saveUserInfo({commit}, userInfo) {
            // 这里可以简化，因为mutations中已经处理了本地存储
            commit("SET_TOKEN", userInfo.token);
            commit("SET_INFO", userInfo);
            commit("SET_NAME", {
                username: userInfo.username,
                realname: userInfo.nickName,
                welcome: "hi,本次登录时间:" + getNowDate(),
            });
        },
        // 新增：退出登录 action
        clearUserInfo({commit}) {
            commit("CLEAR_USER_INFO");
        }
    },
    modules: {},
}
